<template>
  <div v-if="visible" class="tj-pick-mask">
    <div class="tj-pick-box">
      <div class="tj-pick_hd">
        <div class="hd-title">{{ title }}</div>
        <div class="hd-close" @click="clickCloseHandler">
          <svg class="pick-icon" aria-hidden="true">
            <use xlink:href="#icon-tanchuang_icon_delete"></use>
          </svg>
        </div>
      </div>
      <div class="tj-pick_bd">
        <div class="bd_left">
          <ShowPeople
            ref="showPeople"
            :data="options"
            :role-list="props.roleLists"
            :appoint-states="props.appointState"
            :contacts-lists="contactsList"
          ></ShowPeople>
        </div>
        <div class="bd_right">
          <SelectPeople
            :ok-text="okText"
            :close-text="closeText"
            :select-list="selectList"
            @clickOKHandler="clickOKHandler"
            @emptySelectHandler="emptySelectHandler"
            @clickCloseHandler="clickCloseHandler"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'TjPickAndGroup'
};
</script>
<script setup>
import { message } from 'ant-design-vue';
// import './fontIcon/iconfont';
import store from '@/store';
import SelectPeople from './components/SelectPeople/index.vue';
import ShowPeople from './components/ShowPeople/index.vue';
import {
  defineProps,
  defineEmits,
  ref,
  computed,
  provide,
  toRef,
  watch,
  onMounted,
  inject
} from 'vue';
import getAllPeopleAndGroup from '@/utils/getAllPeopleAndGroup';
import getPeoples from '@/utils/getPeople';
const props = defineProps({
  visible: {
    type: Boolean
  },
  contactsList: {
    // 常用联系人数集
    type: Array,
    default: () => []
  },
  roleLists: {
    // 角色数组
    type: Array,
    default: () => []
  },
  title: {
    type: String,
    default: '添加人员'
  },
  okText: {
    type: String,
    default: '确定'
  },
  closeText: {
    type: String,
    default: '取消'
  },
  schoolInfo: {
    type: Object,
    default: () => ({ name: '默认学校', icon: '' })
  },
  options: {
    type: Array,
    default: () => [],
    required: true
  },
  maxCount: {
    type: [Number, String],
    default: '不限'
  },
  appointState: {
    // 是否是选择指定人员
    type: Boolean,
    default: false
  },
  echoData: {
    type: Array,
    default: undefined
  },
  fixData: {
    type: Array,
    default: undefined
  },
  type: {
    type: String,
    default: 'all' // all=>选人和组 people=>选人 group=>选组
  }
});
const allPeople = ref([]);
const allGroup = ref([]);
let contactsList = ref({}); // 常用联系人
onMounted(() => {
  // 是否进行数据回显
  echoHandler();
});

// 回显数据
const echoHandler = () => {
  console.log(55555555555555, props.echoData);
  if (props.echoData?.length > 0) {
    // props.echoData.forEach(t => {
    //   let key = t.userId ? 'userId' : 'categoryId';
    //   if (props.type === 'group' && key === 'userId') return;
    // });
    addOrDelSelectHandler(true, props.echoData, 'userId');
    showPeople.value.getShowPeople();
  }
};
const emit = defineEmits(['update:visible', 'onOK', 'onClose']);

// 选中人员
const selectList = ref([]);
// 已选人数
const numberSelect = ref(0);
// 点击确定
const clickOKHandler = () => {
  let data = [];
  if (props.type === 'people') {
    data = getPeoples([...selectList.value]);
  } else {
    data = [...selectList.value];
  }
  console.log(data);
  emit('onOK', data);
  emit('update:visible', false);
  sessionStorage.removeItem('tabStorageClass');
  sessionStorage.removeItem('classPeople');
  sessionStorage.removeItem('tabStorage');
  store.commit('user/allPeoples', []);
  store.commit('user/contactsList', []);
  selectList.value = [];
  numberSelect.value = 0;
};
// 关闭选人弹窗
const clickCloseHandler = () => {
  selectList.value = [];
  numberSelect.value = 0;
  store.commit('user/allPeoples', []);
  store.commit('user/contactsList', []);
  emit('update:visible', false);
  sessionStorage.removeItem('tabStorage');
  sessionStorage.removeItem('classPeople');
  sessionStorage.removeItem('tabStorageClass');
  emit('onClose');
};
// 添加删除 选中元素 true=>添加 false=>false type:checkAllPeople=>全选取消； allPeople=>全部清除取消
const addOrDelSelectHandler = (bool, valueList, key, type) => {
  console.log('1=======>111', type, bool);
  valueList.forEach(value => {
    value.userName = value.username;
    value.username = value.userName;
    if (bool) {
      // 没有限制时，直接追加
      if (props.maxCount === '不限') {
        let index = selectList.value.findIndex(t => t[key] === value[key]);
        // 保证不存在再进行追加
        if (index === -1) {
          selectList.value.push(value);
          // 选择类型不为分组时 需要计算分组人数
          if (props.type !== 'group' && key === 'categoryId') {
            if (value?.numberPeople) {
              numberSelect.value = Number(numberSelect.value) + Number(value?.numberPeople);
            }
            return;
          }
          numberSelect.value = Number(numberSelect.value) + 1;
        }
        return;
      } else {
        let index = selectList.value.findIndex(t => t[key] === value[key]);
        if (index === -1) {
          if (determineNumberOf(numberSelect.value, props.maxCount)) return;
          if (props.type !== 'group' && key === 'categoryId') {
            aa(value);
          } else {
            if (determineNumberOf(Number(numberSelect.value) + 1)) return;
          }
          selectList.value.push(value);
          if (props.type !== 'group' && key === 'categoryId') {
            if (value?.numberPeople) {
              numberSelect.value = Number(numberSelect.value) + Number(value?.numberPeople);
            }
            return;
          }
          numberSelect.value = Number(numberSelect.value) + 1;
        }
      }
    } else {
      emptySelectHandler(value[key], key, value?.numberPeople, type);
    }
  });
  showPeople.value.getShowPeople(type);
};
const aa = value => {
  if (value?.numberPeople) {
    if (determineNumberOf(Number(numberSelect.value) + Number(value?.numberPeople))) return;
  }
};
// 判断是否超出限制
const determineNumberOf = number => {
  // console.log(666666666, number);
  // console.log(777777, props.maxCount);
  if (Number(number) > Number(props.maxCount)) {
    // message.closeAll();
    // store.state.user.allPeoples.forEach(item=>{
    //     item.disabled=true
    // })
    // console.log(store.state.user.allPeoples);
    // store.commit('user/allPeoples', store.state.user.allPeoples);
    message.error(`选择超出限制人数`);
    return true;
  }
  return false;
};
const showPeople = ref(null);
// 清空所选 id存在=> 删除 or 清空 type:checkAllPeople=>全选取消； allPeople=>全部清除取消
const emptySelectHandler = (id, key, number, type) => {
  console.log(type, '儿回复框上');
  if (id) {
    // 如果删除数据为固定数据return
    if (props.fixData?.length > 0) {
      let bool = props.fixData.findIndex(t => t[key] === id) > -1;
      if (bool) return;
    }
    let index = selectList.value.findIndex(t => t[key] === id);
    if (index > -1) {
      selectList.value.splice(index, 1);
      if (props.type !== 'group' && key === 'categoryId' && Number(numberSelect.value) > 0) {
        if (number) numberSelect.value = Number(numberSelect.value) - Number(number);
        return;
      }
      if (Number(numberSelect.value) > 0) numberSelect.value = Number(numberSelect.value) - 1;
    }
  } else {
    numberSelect.value = 0;
    selectList.value = [];
    // 清空时保存固定数据
    if (props.fixData?.length > 0) {
      props.fixData.forEach(t => {
        let key = t.userId ? 'userId' : 'categoryId';
        if (props.type === 'group' && key === 'userId') return;
        if (key === 'categoryId') {
          if (t?.numberPeople) {
            numberSelect.value = Number(numberSelect.value) + Number(t?.numberPeople);
          }
        } else {
          numberSelect.value = Number(numberSelect.value) + 1;
        }
        selectList.value.push(t);
      });
    }
  }
  if (type === 'allPeople') showPeople.value.getShowPeople();
};

provide('options', toRef(props, 'options'));
provide('numberSelect', numberSelect);
provide('selectList', selectList);
provide('fixData', toRef(props, 'fixData'));
provide('maxCount', toRef(props, 'maxCount'));
provide('type', toRef(props, 'type'));
provide('addOrDelSelectHandler', addOrDelSelectHandler);
provide('contactsListq', props.contactsList);
</script>
<style lang="less">
@import url(./common.less);
@import url(./style/_index.less);
</style>
<style lang="less" scoped>
.tj-pick-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.4);
  overflow: auto;
  //   z-index: 1999;
  z-index: 1001;
  .tj-pick-box {
    width: 776px;
    height: 630px;
    background: #ffffff;
    border-radius: 4px;
    box-shadow: 0px 0px 20px 0px rgba(0, 0, 0, 0.15);
    margin: 5% auto;
    padding: 24px;
    .tj-pick_hd {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16px;
      .hd-title {
        font-size: 18px;
        font-family: Source Han Sans CN, Source Han Sans CN-Medium !important;
        font-weight: 500;
        text-align: LEFT;
        color: rgba(0, 0, 0, 0.8);
        line-height: 26px;
      }
      .hd-close {
        cursor: pointer;
        color: #959ba5;
        &:hover {
          color: #bbc0c6 !important;
        }
      }
    }
    .tj-pick_bd {
      display: flex;
      justify-content: space-between;
      height: 100%;
      > div {
        flex: 1;
        height: 540px;
      }
      .bd_right {
        width: 216px;
        padding-left: 12px;
        border-left: 1px solid rgba(186, 191, 197, 0.4);
      }
      .bd_left {
        margin-right: 12px;
      }
    }
  }
}
</style>
